<template>
  <!-- 我的优惠 -->
  <div class="discount_container">
    <div class="main">
      <nut-tabs v-model="tab_id" title-scroll title-gutter="10">
        <template #titles>
          <div v-for="(item, g) in tab_list" :key="g" :class="['tab_wrap', { tab_active: tab_id == item.id }]"
            @click="changeTab(item.id, g)">
            <span>{{ t(item.label) }}</span>
            <div v-if="item.showDot" class="dot"></div>
			<div v-if="tab_id == item.id" class="line"></div>
          </div>
        </template>
      </nut-tabs>
      <div class="main_content" v-if="!loading">
		<swiper
			direction="horizontal"
			:autoplay="false"
			:autoHeight="true"
			:loop="false"
			:disableOnIntercation="false"
			:touchStartPreventDefault="false"
			slidesPerView="auto"
			:space-between="5"
			:centeredSlides="true"
			class="search_page_swiper"
			@swiper="onSwiperInit"
			@slideChange="handleSwiperChange"
			>
			<swiper-slide v-for="tab in tab_list" :key="tab.id">
				<template v-if="filterDataByTab(tab.id)?.length">
					<div class="list_item" v-for="(item, i) in filterDataByTab(tab.id)" :key="item.id + '_' + i" :style="{
						background: item.bgColor,
					}">
						<div class="left" @click="applyClick(item)">
						<img v-lazy="item.imageIcon" alt="" class="item_img" />
						<div class="text_content">
							<span class="item_label">
								<span :style="{ color: item.textColor }">{{ item.name }}</span>

								<span :style="{ color: item.labelColor }">{{ item.textLabel&&t(item.textLabel) }}</span>
							</span>
						</div>
						</div>
						<div class="apply" @click="receiveClick(item)" v-if="['System', 'VIP_related'].includes(item.tag)">
						{{ t("promo_page_receive") }}
						</div>
						<!-- <div class="apply" @click="applyClick(item)" v-else>
						<span v-if="item.id == 8001"> {{ t("view_details") }}</span>
						<span v-else> {{ t("offer_apply") }}</span>
						</div> -->
					</div>
				</template>
				<div v-else class="no_data">
					<EmptyState :text="t('nomore_data')" :showTips="false" />
				</div>
			</swiper-slide>
		</swiper>
	  </div>
	</div>
		<!-- 弹窗 -->
		<Modal v-model:visible="isShow" :title="modelTitle" @close="handleClose">
			<template #left>
				<div class="to_active" @click="toActive">...</div>
			</template>
			<div class="popup_body">
				<div
					class="tag_item"
					:style="{
						background: itemInfo?.bgColor,
						color: itemInfo?.textColor,
					}"
				>
					<img v-lazy="itemInfo?.imageIcon" alt="" class="item_img" />
					<span>{{ itemInfo?.des ? t(itemInfo?.des) : '' }}</span>
				</div>

				<div class="model_content" v-if="['constant', 'deposit'].includes(itemInfo?.tag)">
					<div class="model_item">
						<span>{{ tab_id == 'constant' ? t('deposit_page_upperLimit') : t('deposit_page_giftAmount') }}：</span>
						<span class="gold">{{ Intl.NumberFormat().format(detailsInfo?.limit) || '--' }}</span>
					</div>
					<div class="model_item" v-if="detailsInfo?.ratio">
						<span>{{ t('first_deposit_revive_gift') }}：</span>
						<span class="gold">{{ detailsInfo?.ratio + '%' || '--' }}</span>
					</div>
					<div class="model_item">
						<span>{{ t('first_deposit_revive_water') }}：</span>
						<span class="gold">{{ detailsInfo?.require + 'x' }}</span>
					</div>
					<div class="model_item">
						<span>{{ t('first_deposit_revive_minimum') }}：</span>
						<span class="gold">{{ Intl.NumberFormat().format(detailsInfo?.threshold) || '--' }}</span>
					</div>
					<div class="model_item_gold" v-if="hasSave">
						<span>{{ t('first_deposit_revive') }}：</span>
						<div>
							<span>{{ t('first_deposit_revive_gift') }}：</span>
							<span class="gold">{{ detailsInfo?.save_ratio + '%' || '--' }}</span>
						</div>
						<div>
							<span>{{ t('first_deposit_revive_water') }}：</span>
							<span class="gold">{{ detailsInfo?.save_require + 'x' }}</span>
						</div>
						<div>
							<span>{{ t('first_deposit_min_amount') }}：</span>
							<span class="gold">{{ Intl.NumberFormat().format(detailsInfo?.save_trigger) || '--' }}</span>
						</div>
					</div>
				</div>
				<div v-else>
					<div class="sys_content">
						<div v-if="itemInfo?.tag=='VIP_related'">{{ t('promo_page_vip', { vip: vipName }) }}</div>
						<div v-else>{{ t('revivalBonusReceived') }}</div>
						<div class="bonus">{{  Intl.NumberFormat().format(itemInfo?.bonus) || '--' }}</div>
					</div>
					
				</div>
				<div>
					<nut-button v-if="['constant', 'deposit'].includes(itemInfo?.tag)" class="submit" @click="submit">{{ t('promo_page_apply') }}</nut-button>
					<nut-button v-else class="submit" @click="submitRecive">{{ t('vip_collect') }}</nut-button>
				</div>
			</div>
		</Modal>

		<!-- 首存300 弹窗 -->
		<nut-popup v-model:visible="firstStorage300Show" style="background-color: transparent; overflow: auto; width: 100vw">
			<first-storage_three v-model="firstStorage300Show" />
		</nut-popup>
		 <!-- 首存弹窗 -->
		 <first-storage v-if="firstStorageShow" v-model:show="firstStorageShow" @close="handleFirstStorageClose" />
		<div>
			<Toast v-model:visible="showToast">{{ toast_value }}</Toast>
		</div>
		<!-- 弹出绑定银行卡提示 -->
		<ShowBindDia v-model:visible="showBindModal"  />
		<!-- <redBagModal ref="redBagModalRef" :avatarUrl="avatarUrl" /> -->
	</div>
</template>

<script setup lang="ts">
import { useRouter } from "vue-router";
import { ref, onMounted, computed, defineAsyncComponent } from "vue";
import { NetPacket } from "@/netBase/NetPacket";
import { useI18n } from "vue-i18n";
import { Local } from "@/utils/storage";
import FirstStorage_three from "@/views/myDiscounts/components/firstStorage_three.vue";
 import FirstStorage from "@/views/firstStorage/index.vue";
import PKwebsocket from "@/lolo/Ws";
import { storeToRefs } from "pinia";
import { User } from "@/store/user.ts";
import pinia from "@/store";
import ShowBindDia from "@/views/deposit/showBindDia.vue";
import EmptyState from '../searchGames/components/EmptyState.vue'
// @ts-ignore
import { Swiper, SwiperSlide } from 'swiper/vue';
import 'swiper/css';
const Toast = defineAsyncComponent(() => import("@/components/Toast.vue"));
const { t } = useI18n();
const router = useRouter();
const isShow = ref(false);
const firstStorageShow = ref(false);
const firstStorage300Show = ref(false);
const modelTitle = ref();
const tab_id = ref("1");
const listData: any = ref([]);
const loading = ref(true);
const showToast = ref(false);
const toast_value = ref("");
const detailsInfo = ref();
const itemInfo: any = ref();
const showBindModal = ref(false);
const styleObj: any = {
	System: {
		des: 'promo_page_System_get',
		imageIcon: '/imgs/myDiscounts/icon1.webp',
		textColor: '#3B47C0',
		textLabel: 'promo_page_System_get',
		color: 'linear-gradient(93.52deg, #D1E1FE 2.39%, #A3B8E4 12.26%, #B8D0FC 47.41%, #EDF3FF 100.56%)',
	},
	constant: {
		des: 'promo_page_constant',
		imageIcon: '/imgs/myDiscounts/icon2.webp',
		textColor: '#365608',
		color: 'linear-gradient(93.52deg, #B3D71D 2.39%, #598A11 12.26%, #7CAF0D 47.41%, #F2FDC7 100.56%)',
	},
	8001: {
		imageIcon: '/imgs/myDiscounts/icon3.webp',
		textColor: '#973207',
		textLabel: '首存二选一,优惠多点',
		pic_link: `/imgs/lang/zh/activity/8001.png`,
		labelColor: '#815651',
		color: 'linear-gradient(93.52deg, #FFE8D2 2.39%, #CC865F 12.26%, #D0A288 47.41%, #F7E8DB 100.56%)',
	},
	9020: {
    des: "promo_page_constant",
    imageIcon: "/imgs/myDiscounts/9020.png",
    textColor: "#313D91",
    color:
      "linear-gradient(93.52deg, #98A7FF 2.39%, #6277E7 12.26%, #8194FE 25.7%, #BFCCFF 100.56%)",
  },
	10010: {
		imageIcon: '/imgs/myDiscounts/icon6.webp',
		textColor: '#A75D13',
		textLabel: '鸿运当头，新年红包',
		labelColor: '#715D48',
		color: 'linear-gradient(93.52deg, #FFDE96 2.39%, #FF9933 12.26%, #FFDE96 33.73%, #FFEFCD 100.56%)',
	},
	8002: {
		des: 'promo_page_constant',
		imageIcon: '/imgs/myDiscounts/icon4.webp',
		textColor: '#563C90',
		textLabel: '首存二选一,优惠多多',
		labelColor: '#6B5E89',
		color: 'linear-gradient(93.52deg, #D8C9F1 2.39%, #A793D1 12.26%, #CBBCF4 47.61%, #EEE3FF 100.56%)',
	},
	deposit: {
		des: 'promo_page_constant',
		imageIcon: '/imgs/myDiscounts/icon4.webp',
		textColor: '#563C90',
		color: 'linear-gradient(93.52deg, #D8C9F1 2.39%, #A793D1 12.26%, #CBBCF4 47.61%, #EEE3FF 100.56%)',
	},
	VIP_related: {
		des: 'promo_page_vip_rel',
		imageIcon: '/imgs/myDiscounts/icon5.webp',
		textColor: '#AE7433',
		textLabel: '请领取您的晋升礼金',
		color: 'linear-gradient(93.52deg, #ffeed2 2.39%, #cca35f 12.26%, #d0b588 47.41%, #f7ecdb 100.56%)',
	},
};

const swiperInstance = ref(null);
const onSwiperInit = (swiper: any) => {
	swiperInstance.value = swiper; // 保存 Swiper 实例
};

const handleSwiperChange = (swiper: any) => {
	const _index = swiper.realIndex;
	tab_id.value = tab_list.value[_index].id;
}

const changeTab = (id: any, index: any) => {
	tab_id.value = id;
	// @ts-ignore
	swiperInstance.value.slideTo(index, 300);
}

// 是否有复活金
const hasSave = computed(() => {
  return (
    detailsInfo.value?.save_ratio ||
    detailsInfo.value?.save_trigger ||
    detailsInfo.value?.save_require
  );
});

const vipName = computed(() => {
  if (itemInfo.value?.tag == "System") {
    return itemInfo.value?.details;
  } else {
    return itemInfo.value?.content.split("_")[2];
  }
});

const tab_list = ref([
  { label: "promo_page_all", id: "1", showDot: false },
  { label: "promo_page_guDing", id: "constant", showDot: false },
  { label: "promo_page_depositZen", id: "deposit", showDot: false },
  { label: "promo_page_system", id: "System", showDot: false },
  { label: "promo_page_vipZen", id: "VIP_related", showDot: false },
]);
const type_obj: any = {
  constant: "promo_page_guDing",
  deposit: "promo_page_depositZen",
  System: "promo_page_system",
  VIP_related: "promo_page_vipZen",
  9020: "promo_page_9020"
};

const filterDataByTab = (tab_id: any) => {
  const list = listData.value.filter(
    (item: any) => item.tag == tab_id && item.name
  );
  return tab_id == "1" ? listData.value : list;
}

// const isDot = (item: any) => {
//     return item.tag == 'System' || item.tag == 'VIP_related'
// }

// 弹窗关闭
const handleClose = () => { };

// 获取优惠数据
const isShouCun = ref(true);
const handleNotify = (rs: any) => {
  console.log("优惠数据", rs);
	const shouCun = rs.dis.filter((item: any) => [8001, 3].includes(item.id));
	tab_list.value[3].showDot = rs.dis.some((item: any) => item.tag == 'System');
	tab_list.value[4].showDot = rs.dis.some((item: any) => item.tag == 'VIP_related');

	// 首存2选1
	if (shouCun.length == 2) {
		isShouCun.value = true;
		listData.value = rs.dis.filter((item: any) => item.name && ![8001, 3].includes(item.id));
		listData.value.push({
			name: '首存活动',
			tag: 'deposit',
			status: 0,
			id: 8002,
		});
	} else {
		isShouCun.value = false;
		listData.value = rs.dis.filter((item: any) => item.name);
	}
  // test 
  // listData.value.push({
  //   id: 9020,
  //   tag: 9020,
  //   name: "签到好礼",
  //   des: "日日签到，天天好彩"
  // })
	listData.value.forEach((item: any) => {
		item.imageIcon = styleObj[item.tag].imageIcon;
		item.bgColor = styleObj[item.tag].color;
		item.textColor = styleObj[item.tag].textColor;
		item.textLabel = styleObj[item.tag]?.textLabel;
		item.des = styleObj[item.tag].des;
		if ([8001,8002, 10010].includes(item.id)) {
			item.imageIcon = styleObj[item.id].imageIcon;
			item.bgColor = styleObj[item.id].color;
			item.textColor = styleObj[item.id].textColor;
			item.textLabel = styleObj[item.id].textLabel;
			item.labelColor = styleObj[item.id].labelColor;
			item.des = styleObj[item.id].des;
			item.pic_link = styleObj[item.id]?.pic_link;
		}
	});

	loading.value = false;

};

// 申请
const applyClick = (data: any) => {
  if (data.id === 8001 || data.id === 8002) {
    if (!isShouCun.value) {
      firstStorage300Show.value = true;
      return;
    }

    // 8001是首存活动的tag
    firstStorageShow.value = true;
    return;
  }
  itemInfo.value = data;
  isShow.value = true;
  modelTitle.value = t(type_obj[data.tag]);

  const query = NetPacket.req_discount_details();
  query.activity_ID = data.id;
  PKwebsocket.instance.send(query, true, {
    callbackName: "msg_notify_discount_details",
    callback: resultDetails,
  });
};
const { bankCardInfoList } = storeToRefs(User(pinia));

// 获取已绑定的银行账号
const getMyBankList = () => {

  const req = NetPacket.req_bank_card_info_list();
  PKwebsocket.instance.send(req, true)
}


// 立即申请
const submit = () => {

  const { bank_card_info_list } = bankCardInfoList.value;
  if (bank_card_info_list.length === 0) {
    showBindModal.value = true;
    return;
  }
  Local.set("curDiscountData", detailsInfo.value); // 当前选择的优惠详情，需要带到充值页面
  router.push("/deposit");
};

// 去活动
const toActive = () => {
	console.log(5555555,itemInfo.value)
  isShow.value = false;
  router.push("/activity");
};

// 立即领取
const receiveClick = (item: any) => {
  itemInfo.value = item;
  modelTitle.value = t(type_obj[item.tag]);
  isShow.value = true;
};

const submitRecive = () => {
  const query = NetPacket.req_get_email_attachments();
  query.email_id = itemInfo.value.details; // 这个 details 才是领取的 id
  PKwebsocket.instance.send(query, true, {
    callbackName: "msg_notify_get_email_attachments",
    callback: resultAttachments,
  });
};

//通知附件领取成功回执
const resultAttachments = (res: any) => {
  showToast.value = true;
  if (res.email_id.includes("#") || res.email_id === "-0") {
    toast_value.value = t("promo_page_applyFail");
  } else {
    // 成功
    toast_value.value = t("promo_page_applySuc");
    const query = NetPacket.req_my_recharge_discount();
    PKwebsocket.instance.send(query, true, {
      callbackName: "msg_notify_my_recharge_discount",
      callback: handleNotify,
    });
    isShow.value = false;
  }
};

// 优惠详情
const resultDetails = (res: any) => {
  detailsInfo.value = res.details;
};

const handleFirstStorageClose = () => {
  firstStorageShow.value = false;
};


onMounted(() => {
  const query = NetPacket.req_my_recharge_discount();
  PKwebsocket.instance.send(query, true, {
    callbackName: "msg_notify_my_recharge_discount",
    callback: handleNotify,
  });
  getMyBankList();
});
</script>

<style lang="scss" scoped>
.discount_container {
  height: 100%;
  overflow: hidden;
  :deep(.swiper-slide) {
	min-height: calc(100 * var(--vh) - 120px);
}
}

.main {
	&:deep(.nut-tabs__titles .nut-tabs__titles-item) {
		min-width: 50px;
		font-size: 12px;
	}

	&:deep(.nut-tabs) {
		padding: 0 10px;
		padding-top: 5px;
	}

	&:deep(.nut-tabs__titles) {
		display: flex;
		justify-content: space-between;
		margin-bottom: unset;
		height:44px;
		 padding: 0 10px;
	}

	// padding: 0 10px;
}

.attention {
  color: #a2a5de;
  font-size: 12px;
  text-align: center;
}

.list_item {
  height: 56px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #ffffff;
  padding: 0 10px;
  margin-top: 10px;
  border-radius: 8px;

  .left {
    flex: 1;
    height: 100%;
    display: flex;
    align-items: center;

    .text_content {
      display: flex;
      flex-direction: column;

      .desc {
        opacity: 0.9;
        font-weight: 400;
        font-size: 12px;
      }
    }

    img {
      width: 42px;
      height: 50px;
    }

    span {
      flex: 1;
      color: #93b4ff;
      font-size: 14px;
      font-weight: 550;
      margin-left: 17px;
      margin-right: 1px;
    }
  }

  .apply {
    background: url(/imgs/myDiscounts/applyBtn.webp) center;
    background-repeat: no-repeat;
    background-size: 100% 100%;
    height: 32px;
    width: 64px;
    display: flex;
    font-size: 12px;
    justify-content: center;
    align-items: center;
  }
}

.model_item span.gold {
  color: #ed8302;
  font-size: 14px;
}

.main_content {
	height: calc(var(--vh) * 100 - 95px);
	// border: 1px solid #f00;
	overflow-y: auto;
	padding: 0 15px;
	padding-bottom: 10px;
}

.no_data {
  display: flex;
  justify-content: center;
  margin-top: 60px;
  font-size: 14px;
}

.popup_body {
  padding: 20px 24px;
}

.model_content {
	display: flex;
	flex-direction: column;
	gap: 8px;

	span {
		font-size: 14px;
		font-weight: 500;
		line-height:21px;

		&:nth-child(1) {
			color: #ffffff;
			font-size: 14px;
		}
	}

	.model_item_gold {
		font-size: 14px;
		font-weight: 500;

		span {
			font-size: 14px;
			font-weight: 500;

			&:nth-child(1) {
				color: #ffffff;
				font-size: 14px;
			}

			&:nth-child(2) {
				color: #9e9ea9;
				font-size: 14px;
			}
		}
	}
}

.submit {
  width: 100%;
  height: 44px;
  border-radius: 8px;
  margin-top: 30px;
}

.sys_content {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #ffffff;
  font-size: 14px;

  .bonus {
    color: #ed8302;
    font-size: 20px;
    margin-top: 10px;
  }
}

.tab_wrap {
	height: 44px;
	line-height: 44px;
	position: relative;
	font-size: 12px;
	overflow: hidden;
	white-space: nowrap;
	text-overflow: ellipsis;
	width: 90px;
	margin-right: 10px;
	text-align: center;
	color: #C6C4F5;
}

.tab_active {
	color: #5b6cff;
	position: relative;

	// &::after {
	// 	content: '';
	// 	position: absolute;
	// 	width: 100%;
	// 	height: 2px;
	// 	line-height:2px;
	// 	bottom: 0px;
	// 	left: 0px;
	// 	border-radius: 2px;
	// 	background: linear-gradient(180deg, #5b6cff 0%, #9e1eff 100%);
	// }
	.line {
		position: absolute;
		width: 100%;
		height: 2px;
		line-height:2px;
		bottom: 2px;
		left: 0px;
		border-radius: 2px;
		background: linear-gradient(180deg, #5b6cff 0%, #9e1eff 100%);
	}
}

.dot {
  position: absolute;
  top: 9px;
  right: 0px;
  width: 6px;
  height: 6px;
  background-color: #fe4a5e;
  border-radius: 50%;
  animation: refresh 2s linear infinite;
}

@keyframes refresh {
  0% {
    opacity: 1;
  }

  50% {
    opacity: 0.3;
  }

  100% {
    opacity: 1;
  }
}

.tag_item {
	width: 100%;
	min-height: 50px;
	border-radius: 10.47px;
	position: relative;
	display: flex;
	// justify-content: center;
	align-items: center;
	font-size: 14px;
	font-weight: 500;
	margin-bottom: 10px;

	.item_img {
		position: absolute;
		left: 10px;
		height: 47px;
		top: 0px;
	}
	span{
		// padding-left: 55px;
		 margin-left: 55px;
	}
}

.to_active {
  cursor: pointer;
  margin-top: 0;
  img {
    margin: 15px 0 0 10px;
    width: 20px;
    height: 20px;
  }
}
.item_label {
	display: flex;
	flex-direction: column;
	align-items: flex-start;
	margin-left: -3px !important;
	span {
		&:nth-child(1) {
			font-size: 14px;
		}
		&:nth-child(2) {
			font-size: 12px;
		}
	}
}
</style>
